using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.ServiceModel;

using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;


namespace TicketSellerService {

    delegate void print(string msg, params Object[] obj);

	public class VendorServerHost {    

        private const int NUMBER_OF_ARGUMENTS = 4;

        private const int VENDOR_NAME = 0;

        private const int SERVER_PORT = 1;

        private const int SEARCH_SERVER_URL = 2;

        private const int FLIGHTS_INPUT_FILE = 3;

		static public void Main( string[] args) {
            print console = Console.WriteLine;

            if ( args.Length != NUMBER_OF_ARGUMENTS)
            {
                console( "Error program intput.");
                console("Expected must parameters: <name> <port> <flight search server> <input file name>");
                return;

            }
            string uri = String.Format("http://localhost:{0}/TicketVendorService", args[SERVER_PORT]);

            try
            {
                Convert.ToInt32(args[SERVER_PORT]);
            }
            catch (InvalidCastException e)
            {
                console( "Incorrect port number. Exiting...");
                console( e.Message);
                return;
            }

            
            string inputFileName = args[FLIGHTS_INPUT_FILE];

            if ( !File.Exists( inputFileName)) {
                console( "Could not find flights input file. Exiting...");
                return;
            }
            console("About to start vendor {0} ticket seller service.", args[VENDOR_NAME]);
            console("Please pay ATTENTION, in order ot be able to register for flight search, server should be up.");
            console("Press any key while you will be ready.");
            Console.ReadLine();
            TicketsDB.getInstance().initialize(args[VENDOR_NAME], inputFileName);
			using( WebServiceHost host = new WebServiceHost( typeof(FlightTicketService), 
			                                         new Uri( uri)) ) {
				
				try {
					host.Open( );
                    EndpointAddress serverAddr = new EndpointAddress( new Uri( "http://" + args[SEARCH_SERVER_URL])); 
                    using (VendorRegistrationClient proxy = new VendorRegistrationClient( new BasicHttpBinding( ), serverAddr))
                    // TODO: Get search server address and setup endpoint accordingly.
                    {
                        console("Registering: " + args[VENDOR_NAME]);
                        proxy.registerVendor(args[VENDOR_NAME], uri);
                    }
                    console("Host opened connection.");
                    console("Endpoints for ticket sellers services.");
                    foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
                    {
                        console("Endpoint ({0}) listening at uri: {1}", endpoint.Name, endpoint.ListenUri);
                    }

					Console.ReadLine( );
                } catch ( EndpointNotFoundException e) {
                    console("Flights search server is down. Try start later, could not register.");
				} catch (InvalidOperationException e) {
					console( e.Message.ToString( ));
					console( e.StackTrace.ToString( )); 
				} finally {
					host.Close( );
				}
			}
		}
	}
}

